package net.xiangcaowuyu.shiro.controller;

import net.xiangcaowuyu.shiro.constant.AuthenConst;
import net.xiangcaowuyu.shiro.entity.ShiroUser;
import net.xiangcaowuyu.shiro.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author laughing
 * @date 2020/10/11
 * @site https://www.lisen.org
 */
@RestController
@RequestMapping("/shiro")
public class ShiroController {

    private final Logger logger = LoggerFactory.getLogger(ShiroController.class);

    @Resource
    ShiroService shiroService;

    @RequestMapping("/findUserByUserCode")
    public ShiroUser findUserByUserCode() {
        String userCode = "lisen";
        ShiroUser shiroUser = shiroService.findUserByCode(userCode);
        return shiroUser;
    }

    @RequestMapping("/login")
    public String login(@RequestParam("userCode") String userCode, @RequestParam("password") String password) {
//        password = new SimpleHash(AuthenConst.HASH_ALGORITHM_NAME,password,AuthenConst.SALT,AuthenConst.HASH_INTERACTIONS).toHex();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userCode, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            logger.error("用户名不存在！", e);
            return "用户名不存在！";
        } catch (AuthenticationException e) {
            logger.error("账号或密码错误！", e);
            return "账号或密码错误！";
        } catch (AuthorizationException e) {
            logger.error("没有权限！", e);
            return "没有权限";
        }
        return "login success";
    }

    @RequestMapping("/index")
    public String index(String userCode, String password) {
        return "index";
    }

    @RequiresPermissions("permission")
    @RequestMapping("/permission")
    public String permission() {
        return "permission";
    }

    @RequiresPermissions("dept:add")
    @RequestMapping("/deptadd")
    public String deptAdd() {
        return "dept:add";
    }

    @RequestMapping("/nopermission")
    public String noPermission() {
        return "noPermission";
    }

}
